<?php
session_start();
$lib_dir = str_ireplace("ajax", "lib", dirname(__FILE__));
require_once $lib_dir.'/config.php';
require_once $lib_dir.'/facebook.php';
require_once $lib_dir.'/util.php';
require_once $lib_dir.'/friend.php';
require_once $lib_dir.'/friends.php';

if(isset($_REQUEST['mode'])){
    $mode = $_REQUEST['mode'];
}else{
    print('{ "error": "Required parameter is missing. Program abort." }');
    exit();
}

if(!isset($_SESSION['fb_session']) && !isset($_REQUEST['signed_request']) ){
    print('{ "error": "Invalid request is detected. Program abort." }');
    exit();
}

$facebook = new Facebook(array(
    'appId' => FB_APP_ID,
    'secret' => FB_APP_SECRET
));

if(isset($_SESSION['fb_session'])){
    $facebook->setSession($_SESSION['fb_session']);        
}

$session = $facebook->getSession();

$friends = null;
if($session){
    try{
        $now = time();	
    	
        $friends = array();
        
        error_log("Elapsed time for getFriends() with ".count($friends)." of friends : ".(time() - $now));
        $now = time();    

        //Get All Data at once
        $response = getAllDataFromFQL($mode);
        
        error_log("Elapsed time for getAllDataFromFQL(".$mode.") : ".(time() - $now));
        $now = time();    
    
        //Messages : mode 1
        if(($mode & MESSAGE_FLAG) === MESSAGE_FLAG){
            $threads = getResultSet("threadQuery", $response);
            $messages = getResultSet("messageQuery", $response);
            processMessages($friends, $threads, $messages);
        }
        
    	//Friends' Posts on my wall : mode 2
        if(($mode & POST_FLAG) === POST_FLAG){
        	$friendsPosts = getResultSet("friendsPostQuery", $response);
            processFriendsPostsOnMyWall($friends, $friendsPosts);          	
        }

        //COMMENT : mode 4
        if(($mode & COMMENT_FLAG) === COMMENT_FLAG){
            //Friends' comments
            $friendsComments = getResultSet("friendsCommentQuery", $response);
        	processFriendsComments($friends, $friendsComments);
        
            //My Comments    
            $myComments = array(
                            getResultSet("myCommentNoteQuery", $response),
                            getResultSet("myCommentStatusQuery", $response),
                            getResultSet("myCommentLinkQuery", $response)
                           );
        
        	processMyComments($friends, $myComments);
        }

        //LIKE : mode 8
        if(($mode & LIKE_FLAG) === LIKE_FLAG){
            //Friends' Likes : mode 8
            $friendsLikes = getResultSet("friendsLikesQuery", $response);
        	processFriendsLikes($friends, $friendsLikes);
        
            //My Likes
            $myLikes = array(
                            getResultSet("myLikeNoteQuery", $response),
                            getResultSet("myLikeStatusQuery", $response),
                            getResultSet("myLikeLinkQuery", $response)
                           );
        
            processMyLikes($friends, $myLikes);
        }
    
    	//sort
    	if(is_array($friends)){
    	    uasort($friends, 'cmp');
    	}    
		
        //JSON encoding
        $json = "[";
    
        $isFirst = true;
        foreach($friends as $f){
            if(!$isFirst){
                $json .= ',';
            }
            $json .= '{';
            $json .= '"fId" : "'.$f->getfId().'",';
            $json .= '"name" : "'.$f->getName().'",';
            $json .= '"score" : "'.$f->getScore().'"';
            $json .= '}';
            $isFirst = false;

        }
    
        $json .= "]";

        //return output
        print $json;
            
    } catch (FacebookApiException $e){
        error_log("getAllDataFromFQL() error : ".(time() - $now));
        print('{"error":"'."Facebook error:".$e->getMessage().'"}');
    }
}
